<?php
require_once('../classes/settings.php');
if(! isset($_GET['term']))exit;

$searchText = $_GET['term'];
$results = array();

$link = @mysql_connect(Settings::DB_HOST,Settings::DB_USER,Settings::DB_PASSWORD);
if($link !== false && @mysql_select_db("vliegtickets", $link)) {

	$res = @mysql_query('
		SELECT
			airport.id_airport          AS aid,
			airport.airport_name        AS airport,
			airport.IATA_code AS abbrev,
			city.city_name           AS city,
			country.country_name        AS country
		FROM
			airports airport
		LEFT JOIN
			cities city ON airport.id_city=city.id_city
		LEFT JOIN
			countries country ON city.id_country=country.id_country
		WHERE
			airport.airport_name LIKE "'.$searchText.'%" OR
			airport.airport_name LIKE "%'.$searchText.'%" OR
			city.city_name    LIKE "'.$searchText.'%" OR
			country.country_name LIKE "'.$searchText.'%"
		ORDER BY
			airport.airport_name ASC
		LIMIT
			5',
		$link
	);

	if($res !== false && @mysql_num_rows($res) >= 1) {
		while($row = @mysql_fetch_assoc($res)) {
			$results[] = array(
				'id' => $row['aid'],
				'label' => sprintf(
					'%s - %s, %s (%s)',
					$row['city'], $row['airport'], $row['country'], $row['abbrev']
				)
			);
		}
	}

	@mysql_close($link);
}

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

exit(json_encode($results));